package cn.zjl.testlogin.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWT;
import cn.zjl.testlogin.entity.User;
import cn.zjl.testlogin.search.ResultOk;
import cn.zjl.testlogin.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    // 登录
    @RequestMapping("login")
    public ResultOk login(@RequestBody User user) {
        if (Objects.isNull(user)){
            return ResultOk.of(1111,"登录信息不允许为空",false);
        } else {
            if (Objects.isNull(user.getUserNo())){
                return ResultOk.of(2222,"工号不允许为空",false);
            }
            if (Objects.isNull(user.getUserPwd())){
                return ResultOk.of(3333,"密码不允许为空",false);
            }
            final QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("user_no",user.getUserNo());
            final User login_user = userService.getOne(userQueryWrapper);
            if (Objects.isNull(login_user)){
                return ResultOk.of(4444,"该用户不存在",false);
            }
            System.err.println("md5密码:"+SecureUtil.md5(user.getUserPwd()));
            if (!Objects.equals(SecureUtil.md5(user.getUserPwd()),login_user.getUserPwd())){
                return ResultOk.of(5555,"密码不正确",false);
            }
            // 密码对的情况下 进行jwt生成token
            String token = JWT.create().setKey("zjl".getBytes()).

                    setPayload("username", login_user.getUserName()).

                    setPayload("pwd", login_user.getUserPwd()).

                    setExpiresAt(DateUtil.offsetDay(DateUtil.date(), 1)).

                    sign();
            if (!Objects.isNull(token) && !Objects.equals("",token)){
                redisTemplate.opsForValue().set("token",token,3, TimeUnit.MINUTES);
            }
            return ResultOk.pass(token);
        }
    }

}
